using System;
using System.Collections;
using System.Collections.Generic;
using UnityEngine;

public class RoleTouchManager : MonoBehaviour
{
    public static RoleTouchManager Instance { get; private set; }
    public bool EnableTouch = true;
    
    public float clickMaxDuration = 0.3f;
    public float clickMaxDistance = 10f;
    
    public LayerMask interactableLayers = ~0;
    
    private Dictionary<CapsuleCollider2D, SkeletonTouchUtility> _touchDict;

    private SkeletonTouchUtility _currentUtility;

    private Camera mainCamera;
    private Vector2 startMousePosition;
    private Vector2 currentMousePosition;
    private float clickStartTime;
    private bool isDragging = false;
    
    private void Awake()
    {
        Instance = this;
        
        SkeletonTouchUtility[] utilities = transform.GetComponentsInChildren<SkeletonTouchUtility>();
        _touchDict = new();
        foreach (var utility in utilities)
        {
            _touchDict.Add(utility.GetComponent<CapsuleCollider2D>(),utility);
        }
        
        mainCamera = Camera.main;
    }

    // Update is called once per frame
    void Update()
    {
        if(!EnableTouch) return;
        
        if (Input.GetMouseButtonDown(0))
        {
            StartInteraction();
        }

        if (_currentUtility != null && Input.GetMouseButton(0))
        {
            ContinueInteraction();
        }

        if (_currentUtility != null && Input.GetMouseButtonUp(0))
        {
            EndInteraction();
        }
    }
    
    private void StartInteraction()
    {
        Vector3 mousePosition = Input.mousePosition;
        startMousePosition = mousePosition;
        clickStartTime = Time.time;
        
        // 检测点击的对象
        Ray ray = mainCamera.ScreenPointToRay(mousePosition);
        RaycastHit2D hit = Physics2D.GetRayIntersection(ray, Mathf.Infinity, interactableLayers);
        Debug.DrawRay(ray.origin, ray.direction * 1000f, Color.red,5f);
        
        _currentUtility = null;
        if (hit.collider != null && _touchDict.TryGetValue(hit.collider as CapsuleCollider2D, out var value))
        {
            _currentUtility = value;
            var z = _currentUtility.transform.position.z - mainCamera.transform.position.z;
            Vector2 worldStartPos = mainCamera.ScreenToWorldPoint(new Vector3(startMousePosition.x, startMousePosition.y,z));
            Vector2 worldCurrentPos = mainCamera.ScreenToWorldPoint(new Vector3(currentMousePosition.x, currentMousePosition.y,z));
            _currentUtility?.OnPointerDown(worldCurrentPos);
            Debug.DrawRay(ray.origin, ray.direction * 100000f, Color.red, 5f);
        }
    }

    private void ContinueInteraction()
    {
        currentMousePosition = Input.mousePosition;
        var z = _currentUtility.transform.position.z - mainCamera.transform.position.z;
        Vector2 worldStartPos = mainCamera.ScreenToWorldPoint(new Vector3(startMousePosition.x, startMousePosition.y,z));
        Vector2 worldCurrentPos = mainCamera.ScreenToWorldPoint(new Vector3(currentMousePosition.x, currentMousePosition.y,z));
        
        // 检查是否开始拖拽
        if (!isDragging)
        {
            float dragDistance = Vector2.Distance(startMousePosition, currentMousePosition);
            if (dragDistance > clickMaxDistance)
            {
                StartDragging(worldStartPos, worldCurrentPos);
            }
        }
        
        // 持续拖拽
        if (isDragging)
        {
            if (_currentUtility.limitPosInArea)
            {
                worldCurrentPos = _currentUtility.ApplySimpleEllipticalConstraint(worldCurrentPos);
            }
            
            if (!_currentUtility.CheckLimitArea(worldCurrentPos))//不在拖拽范围内结束拖拽
            {
                // 结束拖拽
                Debug.Log("不在拖拽范围内结束拖拽");
                _currentUtility?.OnEndDrag(worldStartPos, worldCurrentPos);
                isDragging = false;
                _currentUtility = null;
                return;
            }
            
            _currentUtility?.OnDrag(worldStartPos, worldCurrentPos);
        }
    }

    private void EndInteraction()
    {
        var z = _currentUtility.transform.position.z - mainCamera.transform.position.z;
        Vector2 worldStartPos = mainCamera.ScreenToWorldPoint(new Vector3(startMousePosition.x, startMousePosition.y, z));
        Vector2 worldEndPos = mainCamera.ScreenToWorldPoint(new Vector3(currentMousePosition.x, currentMousePosition.y, z));
        
        if (isDragging)
        {
            // 结束拖拽
            _currentUtility?.OnEndDrag(worldStartPos, worldEndPos);
            isDragging = false;
        }
        else
        {
            // 检查是否为有效点击
            float clickDuration = Time.time - clickStartTime;
            float clickDistance = Vector2.Distance(startMousePosition, currentMousePosition);
            
            if (clickDistance <= clickMaxDistance)
            {
                if (clickDuration <= clickMaxDuration)
                {
                    _currentUtility?.OnPointerClick(worldEndPos);
                }
                else
                {
                    _currentUtility?.OnPointerUp(worldEndPos);
                }
                Debug.Log("点击对象: " + _currentUtility.name);
            }
        }
        
        _currentUtility = null;
    }
    
    void StartDragging(Vector2 startPos, Vector2 currentPos)
    {
        isDragging = true;
        _currentUtility?.OnBeginDrag(startPos, currentPos);
        Debug.Log("开始拖拽: " + _currentUtility.name);
    }
}
